package com.feilong.edgeAI.utils;

import static android.content.Context.CLIPBOARD_SERVICE;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

import static com.feilong.edgeAI.speech.RecordeHelper.isRecording;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.feilong.edgeAI.BuildConfig;
import com.feilong.edgeAI.R;
import com.feilong.edgeAI.model.FeilongRespone;
import com.feilong.edgeAI.service.AewmeService;
import com.feilong.edgeAI.service.TcpClient;
import com.google.gson.Gson;
import com.iflytek.aikit.core.JLibrary;
import com.xuexiang.xutil.file.ZipUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by【仿脑科技】
 *
 * @Author: potato
 * @CreateDate: 2023/10/17 17:00
 */
public class AppUtils {
    private static final String TAG = "AppUtils";

    /**
     * 高德地图
     */
    public static boolean openGaode(Context context, String destination) {
        try {
            if (isAppInstalled(context, "com.autonavi.minimap")) {
                Intent intent = new Intent(
                        "android.intent.action.VIEW",
                        android.net.Uri.parse(
                                "androidamap://route?sourceApplication=应用名称" + "&dname=" + destination
                                        + "&dev=0" + "&t=1"));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //百度
    private void goToBaidu(Context context, String destination) {
//        Intent intent = Intent.getIntent("intent://map/direction?destination=latlng:" + latLng + "|name:" + address + "&mode=driving&src=某某公司#Intent;" + "scheme=bdapp;package=com.baidu.BaiduMap;end");
//        context.startActivity(intent);
    }

    //haiwai
    public static boolean openApp(Context context, String name) {
        if (name.equals("蓝牙")) {
            openBluetooth(context);
            return true;
        }
        if (name.equals("相机")) {
            startImageCapture(context);
            return true;
        }
        if (name.equals("相册")) {
            startPicture(context);
            return true;
        }
        if (name.equals("摄像机")) {
            startVideoCapture(context);
            return true;
        }
        String pkg = "";
        switch (name) {
            case "百度":
                pkg = "com.baidu.searchbox";
                break;
            case "微信":
                pkg = "com.tencent.mm";
                break;
            case "淘宝":
                pkg = "com.taobao.taobao";
                break;
            case "京东":
                pkg = "com.jingdong.app.mall";
                break;
            case "抖音":
                pkg = "com.ss.android.ugc.aweme";
                break;
            case "支付宝":
                pkg = "com.eg.android.AlipayGphone";
                break;
            case "今日头条":
                pkg = "com.ss.android.article.news";
                break;
            case "日历":
                pkg = "com.freeme.zmcalendar";
                break;
            case "计算器":
                pkg = "com.freeme.calculator";
                break;
            case "记事本":
                pkg = "com.freeme.freemenote";
                break;
            case "收音机":
                pkg = "com.android.fmradio";
                break;
            case "录音机":
                pkg = "com.android.soundrecorder";
                break;
            case "高德地图":
                pkg = "com.autonavi.minimap";
                break;
            default:

                break;
//            case "相机":
//                pkg = "com.knight.cameraone";
//                break;
        }
        if (TextUtils.isEmpty(pkg)) {
            PackageInfo packageInfo = getPackageInfo(context, name);
            if (packageInfo != null) {
                pkg = packageInfo.packageName;
            }
        }

        Log.d(TAG, "openApp: " + pkg);
//        if(name.equals("微信")){
//            openAppByPkg(context,"com.tencent.mm");
//        }
        if (!pkg.isEmpty() && isAppInstalled(context, pkg)) {
//        if (!pkg.isEmpty() && hasInstalled(context, pkg)) {
            try {
                Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkg);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    public static void openAppByPkg(Context context, String pkgname) {
        Log.d(TAG, "openAppByPkg: " + pkgname);
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkgname);
       /* if(null == intent){
            startExagear(context);
            return;
        }*/
        if (null != intent && intent.resolveActivity(context.getPackageManager()) != null) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    public static void openBluetooth(Context context) {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            // 设备不支持蓝牙
        } else if (!mBluetoothAdapter.isEnabled()) {
            // 蓝牙未打开，请求打开蓝牙
//            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            enableBtIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(enableBtIntent);
            mBluetoothAdapter.enable();
        } else {
            // 蓝牙已打开，可以进行后续操作
        }
    }

    public static void closeBluetooth() {
        // 获取默认的BluetoothAdapter
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// 确保BluetoothAdapter不为空并且已经开启
        if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
            // 关闭蓝牙
            mBluetoothAdapter.disable();
        }
    }

//    public static final String exagearpkg = "com.eltechs.ed";


    //haiwai
    public static boolean startTermux(Context context) {
        Log.d(TAG, "startTermux: ");
        String package_name = AewmeService.EXAGEAR_PKG;
//        String package_name = AewmeService.TERMUX_PKG;
        boolean install = isAppInstalled(context, package_name);
//        boolean install = hasInstalled(context, package_name);
//        boolean install = hasInstalled(context, AewmeService.TERMUX_PKG);
        if (install) {
//            String activity_path = "com.eltechs.ed.activities.EDStartupActivity";
            String activity_path = "com.termux.app.TermuxActivity";
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName(package_name, activity_path);
            intent.setComponent(comp);
            context.startActivity(intent);
            Log.d(TAG, "startTermux: startActivity");
        }
        return install;
    }

    public static boolean isIntallTermux(Context context) {
        String package_name = AewmeService.EXAGEAR_PKG;
        boolean install = isAppInstalled(context, package_name);
        return install;
    }

/*    public static boolean startExagear1(Context context) {
        Log.d(TAG, "startExagear: ");
//        String package_name = AewmeService.TERMUX_PKG;
        String package_name = AewmeService.EXAGEAR_PKG;
        boolean install = hasInstalled(context, package_name);
//        boolean install = hasInstalled(context, AewmeService.TERMUX_PKG);
        if (install) {
            String activity_path = "com.eltechs.ed.activities.EDStartupActivity";
//            String activity_path = "com.termux.app.TermuxActivity";
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName(package_name, activity_path);
            intent.setComponent(comp);
            context.startActivity(intent);
            Log.d(TAG, "startExagear: startActivity");
        }
        return install;
    }*/

    public static boolean hasInstalled(Context context, String pkg) {
        PackageManager manager = context.getPackageManager();
        List<PackageInfo> pkgList = manager.getInstalledPackages(0);
        for (int i = 0; i < pkgList.size(); i++) {
            PackageInfo pI = pkgList.get(i);
//            Log.d(TAG, "hasInstalled: name="+pI.packageName);
            if (pI.packageName.equalsIgnoreCase(pkg))
                return true;
        }
        return false;
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        try {
            packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public static void callPhone(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + phone));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void baiduSearch(Context context, String searchKeyword) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("baiduapp://search?query=" + searchKeyword));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setData(Uri.parse("http://www.baidu.com"));
//        context.startActivity(intent);
    }

    public static void sendEmail(Context context) {
        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:example@example.com"));
        intent.putExtra(Intent.EXTRA_SUBJECT, "邮件主题");
        intent.putExtra(Intent.EXTRA_TEXT, "邮件正文");
        context.startActivity(Intent.createChooser(intent, "发送邮件..."));

    }

    public static void calander(Context context) {
        Intent calendarIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("content://calendar/events"));
        context.startActivity(calendarIntent);
    }

    public static void todoist(Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.todoist.com/"));
        context.startActivity(intent);
    }

    public static void sdcard(Context context) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

        context.startActivity(intent);
    }

    public static void Settings(Context context) {
        Intent intent = new Intent(Settings.ACTION_SETTINGS);

        context.startActivity(intent);
    }

    public static void netSettings(Context context) {
        Intent intent = new Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS);

        context.startActivity(intent);
    }

    public static void devinfo(Context context) {
        Intent intent = new Intent(Settings.ACTION_DEVICE_INFO_SETTINGS);

        context.startActivity(intent);
    }

    public static void sms_body(Context context) {
        Intent smsIntent = new Intent(Intent.ACTION_VIEW);
        smsIntent.setType("vnd.android-dir/mms-sms");
        smsIntent.putExtra("address", "+123456789");
        smsIntent.putExtra("sms_body", "Hello World!");

        context.startActivity(smsIntent);
    }

    public static void sendMessageToWeChatFriendByName(Context context, String friendName, String content) {
        try {
            // 创建微信的聊天页面Intent
            Uri uri = Uri.parse("weixin://dl/chat??nickname=" + URLEncoder.encode(friendName, "UTF-8"));
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setPackage("com.tencent.mm");

            // 将要发送的消息放入剪贴板
            ClipboardManager clipboard = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Label", content);
            clipboard.setPrimaryClip(clip);

            // 启动Intent
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendWechat(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void goHome(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static boolean isAppRunning(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (am != null) {
            // 获取正在运行的进程列表
            List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();
            if (processes != null) {
                for (ActivityManager.RunningAppProcessInfo process : processes) {
                    if (process.processName.equals(packageName)) {
                        // 找到对应的进程，说明App正在运行
                        return true;
                    }
                }
            }
        }
        // 没有找到对应的进程，说明App没有运行
        return false;
    }

    public static void startImageCapture(Context context) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    public static void startVideoCapture(Context context) {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    public static void startPicture(Context context) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    public static void closeAction(Context context, String name) {
        if (name.equals("应用")) {
            AppUtils.goHome(context);
        } else {
//            killApp(context,name);
        }
    }

    public static void killApp(Context context, String packageName) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setPackage(packageName);
        context.startActivity(intent);
    }

    public static void closeApp(Context context, String name) {
        String packageName = getPackageInfo(context, name).packageName;
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager packageManager = context.getPackageManager();

        try {
            // 获取应用的主活动
            Intent intent = packageManager.getLaunchIntentForPackage(packageName);
            if (intent == null) {
                // 找不到应用的主活动
                return;
            }
            ResolveInfo resolveInfo = packageManager.resolveActivity(intent, 0);
            if (resolveInfo == null) {
                // 找不到应用的主活动的解析信息
                return;
            }
            String mainActivity = resolveInfo.activityInfo.name;

            // 杀死应用的主活动
            activityManager.killBackgroundProcesses(packageName);
//            activityManager.restartPackage(packageName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static PackageInfo getPackageInfo(Context context, String name) {
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> list2 = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);

        int j = 0;

        for (PackageInfo packageInfo : list2) {
            //得到手机上已经安装的应用的名字,即在AndriodMainfest.xml中的app_name。
            String appName = packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
            //得到手机上已经安装的应用的图标,即在AndriodMainfest.xml中的icon。
            Drawable drawable = packageInfo.applicationInfo.loadIcon(context.getPackageManager());
            //得到应用所在包的名字,即在AndriodMainfest.xml中的package的值。
            String packageName = packageInfo.packageName;
            Log.d(TAG, "getPackageInfo: packageName=" + packageName + " appName= " + appName);
            if (appName.equals(name)) {
                return packageInfo;
            }
        }
        return null;
    }

    private static Map<String, String> packageInfos = new HashMap<>();

    public static String[] getPackageInfo(Context context) {
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> list2 = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);

        List<PackageInfo> datas = new ArrayList<>();
        for (int i = 0; i < list2.size(); i++) {
            PackageInfo packageInfo = list2.get(i);
            //得到手机上已经安装的应用的名字,即在AndriodMainfest.xml中的app_name。
            String appName = packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
            //得到手机上已经安装的应用的图标,即在AndriodMainfest.xml中的icon。
            Drawable drawable = packageInfo.applicationInfo.loadIcon(context.getPackageManager());
            //得到应用所在包的名字,即在AndriodMainfest.xml中的package的值。
            String packageName = packageInfo.packageName;
//            arr[i]=packageInfo.packageName;

            if (appName.length() < 20
                    && !packageName.equals(BuildConfig.APPLICATION_ID)
                    && !packageName.equals("com.baidu.input")) {
                datas.add(packageInfo);
                packageInfos.put(packageName, appName);
            }
//            Log.d(TAG, "packageName: "+packageName+"  name="+appName);
        }
        String[] arr = new String[datas.size()];
        for (int i = 0; i < datas.size(); i++) {
            PackageInfo packageInfo = datas.get(i);
            arr[i] = packageInfo.packageName;
        }
        return arr;
    }

    public static void getRunningApps(Context context) {
        ActivityManager actManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> procInfos = actManager.getRunningAppProcesses();
        PackageManager packManager = context.getPackageManager();

        for (ActivityManager.RunningAppProcessInfo procInfo : procInfos) {
            try {
                String packname = procInfo.pkgList[0];
                ApplicationInfo appInfo = packManager.getApplicationInfo(packname, 0);
                String appName = appInfo.loadLabel(packManager).toString();
                if (procInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    // 当前在前台运行的应用程序
                    Log.d(TAG, "当前在前台运行的应用程序: appName=" + appName);
//                    System.out.println("当前在前台运行的应用程序: " + appName);
                } else if (procInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    // 在后台运行的应用程序
//                    System.out.println("在后台运行的应用程序: " + appName);
                    Log.d(TAG, "在后台运行的应用程序: appName=" + appName);
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getPhoneNumberByName(Context context, String contactName) {
        if (TextUtils.isEmpty(contactName)) {
            return null;
        }
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range") String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//                displayName = TextUtil.getPinyin(displayName).replaceAll(" ","");
                if (displayName != null && displayName.equalsIgnoreCase(contactName)) {
                    @SuppressLint("Range") String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    if (contactId != null) {
                        Cursor phoneCursor = contentResolver.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                new String[]{contactId},
                                null);
                        if (phoneCursor != null && phoneCursor.moveToNext()) {
                            @SuppressLint("Range") String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            if (phoneNumber != null) {
                                phoneCursor.close();
                                return phoneNumber;
                            }
                        }
                        if (phoneCursor != null) {
                            phoneCursor.close();
                        }
                    }
                }
            }
            cursor.close();
        }
        return null;
    }

    public static String getPhoneNumberByPinyin(Context context, String contactName) {
        if (TextUtils.isEmpty(contactName)) {
            return null;
        }
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range") String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                displayName = TextUtil.getPinyin(displayName).replaceAll(" ", "");
                if (displayName != null && displayName.equalsIgnoreCase(contactName)) {
                    @SuppressLint("Range") String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    if (contactId != null) {
                        Cursor phoneCursor = contentResolver.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                new String[]{contactId},
                                null);
                        if (phoneCursor != null && phoneCursor.moveToNext()) {
                            @SuppressLint("Range") String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            if (phoneNumber != null) {
                                phoneCursor.close();
                                return phoneNumber;
                            }
                        }
                        if (phoneCursor != null) {
                            phoneCursor.close();
                        }
                    }
                }
            }
            cursor.close();
        }
        return null;
    }

    public static String getContactId(Context context, String contactName) {
        if (TextUtils.isEmpty(contactName)) {
            return null;
        }
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range") String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//                displayName = TextUtil.getPinyin(displayName).replaceAll(" ","");
                if (displayName != null && displayName.equalsIgnoreCase(contactName)) {
                    @SuppressLint("Range") String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    return contactId;
                }
            }
            cursor.close();
        }
        return null;
    }

    public static void updateContact(Context context, String contactId, String phoneNumber) {
        Uri uri = Uri.parse("content://com.android.contacts/data");//对data表的所有数据操作
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put("data1", phoneNumber);
        resolver.update(uri, values, "mimetype=? and raw_contact_id=?", new String[]{"vnd.android.cursor.item/phone_v2", contactId});
    }

    public static void insertContact(Context context, String name, String phone) {
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        long contact_id = ContentUris.parseId(resolver.insert(uri, values));
        //插入data表
        uri = Uri.parse("content://com.android.contacts/data");
        //add Name
        values.put("raw_contact_id", contact_id);
        values.put(ContactsContract.Contacts.Data.MIMETYPE, "vnd.android.cursor.item/name");
        values.put("data1", name);
        resolver.insert(uri, values);
        values.clear();
        //add Phone
        values.put("raw_contact_id", contact_id);
        values.put(ContactsContract.Contacts.Data.MIMETYPE, "vnd.android.cursor.item/phone_v2");
        values.put("data1", phone);
        resolver.insert(uri, values);
    }

    public static void deleteContact(Context context, String name) {
        //根据姓名求id
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Data._ID}, "display_name=?", new String[]{name}, null);
        if (cursor.moveToFirst()) {
            int id = cursor.getInt(0);
            //根据id删除data中的相应数据
            resolver.delete(uri, "display_name=?", new String[]{name});
            uri = Uri.parse("content://com.android.contacts/data");
            resolver.delete(uri, "raw_contact_id=?", new String[]{id + ""});
        }
    }


    public static void sendSms(Context context, String phoneNumber, String message) {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNumber, null, message, null, null);
        Toast.makeText(context, "短信已发送", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "sendSms: phoneNumber=" + phoneNumber + "  message= " + message);
        Log.d(TAG, "sendSms: message.length=" + message.length());
        Log.d("Service", "sendSms: 短信已发送");
    }


    public static boolean containsChineseCharacter(String str) {
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (isChineseCharacter(c)) {
                return true;
            }
        }
        return false;
    }

    private static boolean isChineseCharacter(char c) {
        // 汉字的Unicode编码范围是0x4E00到0x9FA5
        return c >= 0x4E00 && c <= 0x9FA5;
    }

    public static void openZhiFuBaoScan(Context context) {
        Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=10000007");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void openWeChatScan(Context context) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI"));
        intent.putExtra("LauncherUI.From.Scaner.Shortcut", true);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.intent.action.VIEW");
        context.startActivity(intent);
    }

    public static void getCurrentActivity(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();
        Log.e(TAG, "getCurrentActivity: processes=" + processes.size());
        for (ActivityManager.RunningAppProcessInfo process : processes) {
            if (process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                // 当前活动
                String activeProcessName = process.processName;
                // 获取当前活动的完整类名
                String activeClassName = context.getPackageManager().getNameForUid(process.uid);
                Log.e(TAG, "getCurrentActivity: activeProcessName=" + activeProcessName);
                Log.e(TAG, "getCurrentActivity: activeClassName=" + activeClassName);
            }
        }
    }

    public static void stopAppByKill(Context context, String packageName) {
        ActivityManager mActivityManager = (ActivityManager)
                context.getSystemService(Context.ACTIVITY_SERVICE);
        mActivityManager.killBackgroundProcesses(packageName);
    }

    public static void forceStopPackage(Context context, String packageName) {
        Log.i(TAG, "forceStopPackage packageName = " + packageName);
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        Method forceStopPackage = null;
        try {
            forceStopPackage = activityManager.getClass().getDeclaredMethod("forceStopPackage", String.class);
            forceStopPackage.setAccessible(true);
            forceStopPackage.invoke(activityManager, packageName);
        } catch (NoSuchMethodException e) {
            Log.e(TAG, "forceStopPackage NoSuchMethodException error = " + e.getMessage());
        } catch (IllegalAccessException e) {
            Log.e(TAG, "forceStopPackage IllegalAccessException error = " + e.getMessage());
        } catch (InvocationTargetException e) {
            Log.e(TAG, "forceStopPackage InvocationTargetException error = " + e.getMessage());
        }

    }

    public static boolean checkAccess(Context context) {
        return AewmeService.getInstance().checkAccessibilityEnabled(context.getResources().getString(R.string.app_name));
    }

    public static void setScreenOn1(Context context) {
//        KeyguardManager keyguardManager = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);
//        KeyguardLock keyguardLock = keyguardManager.newKeyguardLock(LOCK_TAG);
//        keyguardLock.disableKeyguard();
    }

    public static void setScreenOn(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "TAG");
        wakeLock.acquire();
    }

    /**
     * 执行命令
     */
    public static String execCommand(String cmd) {
        Log.e(TAG, "runCmd: " + cmd);
        if (TextUtils.isEmpty(cmd) || cmd.length() < 11) {
            return "";
        }
        String cmdHead = cmd.substring(0, 9);
        if (!"adb shell".equals(cmdHead)) {
            return "";
        }
        return execRootCmd(cmd);
    }

    /**
     * 执行按键命令
     */
    public static void execKeyevent(String code) {
        execCommand("adb shell input keyevent " + code);
    }

    /**
     * 执行命令并且输出结果
     */
    public static String execRootCmd(String cmd) {
        String content = "";
        try {
            cmd = cmd.replace("adb shell", "");
            Process process = Runtime.getRuntime().exec(cmd);
            Log.e(TAG, "process " + process.toString());
            content = process.toString();
        } catch (Exception e) {
            Log.d(TAG, "exception " + e.toString());
            e.printStackTrace();
        }
        return content;
    }

    /**
     * 检查是否息屏
     */
    public static boolean checkScreenOn(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = pm.isScreenOn();//如果为true，则表示屏幕“亮”了，否则屏幕“暗”了。
        Log.d(TAG, "checkScreenOn: " + isScreenOn);
        return isScreenOn;
    }


    public static void clearMemory(Context context) {
        // 获取当前应用的 ActivityManager 对象
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        // 获取当前 App 的进程信息KILL_BACKGROUND_PROCESSES
        List<ActivityManager.RunningAppProcessInfo> processList = activityManager.getRunningAppProcesses();

        // 遍历进程信息，杀死其他进程
        for (ActivityManager.RunningAppProcessInfo processInfo : processList) {
            if (!processInfo.processName.equals("com.feilong.edgeAI") && !processInfo.processName.equals(AewmeService.EXAGEAR_PKG)) {
                activityManager.killBackgroundProcesses(processInfo.processName);
                Log.d(TAG, "clearMemory: " + processInfo.processName + " name=" + packageInfos.get(processInfo.processName));
            }
        }
    }

    public static void copyAssetFile(Context context) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                AssetManager assetManager = context.getAssets();
                try {
                    InputStream is = assetManager.open("xunfei.zip");
                    String rootPath = Environment.getExternalStorageDirectory().getPath();
                    String zipPath = rootPath + "/xunfei.zip";
                    FileOutputStream fos = new FileOutputStream(zipPath);
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = is.read(buffer)) > 0) {
                        fos.write(buffer, 0, length);
                    }
                    fos.flush();
                    fos.close();
                    is.close();
                    List<File> files = ZipUtils.unzipFile(zipPath, rootPath);
//                    Log.d(TAG, "copyAssetFile: "+files.size());
//                    unzip(zipPath,rootPath);
                    new File(zipPath).delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public static void copyAssetsDirToSDCard(Context context, String assetsDirName, String sdCardPath) {

        Log.d(TAG, "copyAssetsDirToSDCard() called with: context = [" + context + "], assetsDirName = [" + assetsDirName + "], sdCardPath = [" + sdCardPath + "]");
        try {
//            File dir = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+".iflytek");
//            if(!dir.exists()){
//                dir.mkdirs();
//            }
            String list[] = context.getAssets().list(assetsDirName);
            if (list.length == 0) {
                InputStream inputStream = context.getAssets().open(assetsDirName);
                byte[] mByte = new byte[1024];
                int bt = 0;
                String path = sdCardPath + File.separator
                        + assetsDirName.substring(assetsDirName.lastIndexOf('/'));
                path = path.replaceAll("diriflytek", ".iflytek");
                File file = new File(path);
                File parent = file.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }
                if (!file.exists()) {
                } else {
                    file.delete();
                }
                file.createNewFile();
                FileOutputStream fos = new FileOutputStream(file);
                while ((bt = inputStream.read(mByte)) != -1) {
                    fos.write(mByte, 0, bt);
                }
                fos.flush();
                inputStream.close();
                fos.close();
            } else {
                String subDirName = assetsDirName;
                if (assetsDirName.contains("/")) {
                    subDirName = assetsDirName.substring(assetsDirName.lastIndexOf('/') + 1);
                }
                sdCardPath = sdCardPath + File.separator + subDirName;
                File file = new File(sdCardPath);
                if (!file.exists())
                    file.mkdirs();
                for (String s : list) {
                    copyAssetsDirToSDCard(context, assetsDirName + File.separator + s, sdCardPath);
                }
            }
        } catch (
                Exception e) {
            e.printStackTrace();
        }
    }

    public static long getFolderSize(File folder) {
        long size = 0;
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    size += file.length();
                } else {
                    size += getFolderSize(file);
                }
            }
        }
        return size;
    }

    public static boolean getIflyFileExist() {
        String rootPath = Environment.getExternalStorageDirectory().getPath();
        File iflytek = new File(rootPath + "/.iflytek");
        long len = AppUtils.getFolderSize(iflytek);
        if (!iflytek.exists() || len < 500000000) {
            return false;
        }
        return true;
    }
    public static boolean checkIflyFile() {//离线翻译更新资料
        String rootPath = Environment.getExternalStorageDirectory().getPath();
        File iflytek = new File(rootPath + "/.iflytek/itrans/resource/nmt_core/cnen/e2f45e4b7_1.0.1_cnen.res.bin");
        File iflytek1 = new File(rootPath + "/.iflytek/itrans/resource/nmt_core/encn/e5e1afbaa_1.0.1_encn.res.bin");
        Log.d(TAG, "run:cnen.res.bin.exists()= " + iflytek.exists());
        Log.d(TAG, "run:cnen.res.bin.len= " + iflytek.length());
        if(!iflytek.exists()||iflytek.length()!=30996808){
            return false;
        }
        if(!iflytek1.exists()||iflytek1.length()!=31017896){
            return false;
        }
        return true;
    }

    public static boolean isLocationEnabled(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return isGpsEnabled || isNetworkEnabled;
    }

    public static boolean checkAlive(Context context, String packageName) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            long endTime = System.currentTimeMillis();
            long startTime = endTime - TimeUnit.MINUTES.toMillis(1); // 查询过去5分钟的数据

            List<UsageStats> stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);

            for (UsageStats usageStats : stats) {
                if (packageName.equals(usageStats.getPackageName())) {
                    return true;
                    // 如果存在记录并且lastTimeUsed接近当前时间，则可推测应用可能还在运行或刚刚关闭不久
                }
            }
        }
        return false;
    }

    public static void setSleepTime(Context context, int desiredTimeout) {
        // 获取ContentResolver对象
        ContentResolver resolver = context.getContentResolver();

// 设置休眠超时（单位是毫秒）

// 修改系统设置以更改屏幕关闭延迟
        Settings.System.putInt(resolver,
                Settings.System.SCREEN_OFF_TIMEOUT,
                desiredTimeout);

// 提交设置更改
//        resolver.notifyChange(Settings.System.SCREEN_OFF_TIMEOUT, null);
    }

    public static void startApp(Context context, String packageName, String className) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//可选
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//可选
        ComponentName comp = new ComponentName(packageName, className);
        intent.setComponent(comp);
        context.startActivity(intent);

    }

    public static void searchBaidu(Context context, String keyword) {
        String searchUrl = "https://www.baidu.com/s?wd=" + Uri.encode(keyword);

// 创建意图并设置数据
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(searchUrl));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//可选

// 判断是否有应用可以处理此意图
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    public static void startAppByPackageName(Context context, String packageName) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    public static void reStartSelf(Context context) {
        isRecording = false;
        Intent i = context.getPackageManager()
                .getLaunchIntentForPackage(context.getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
        System.exit(0);
    }

    public static void initFeilong() {
        Locale locale = Locale.getDefault();
        String language = locale.getLanguage();
        String country = locale.getCountry();
        FeilongRespone request = new FeilongRespone("0", "init");
        request.setIfly_ID(JLibrary.getInst().getDeviceId());
        request.setLanguage(language + "_" + country);
        TcpClient.sendTcpMessage(new Gson().toJson(request));
        Log.d(TAG, "initFeilong: " + new Gson().toJson(request));
    }

    public static void autoInstallApk(Context context, File file) {
        try {
            String[] args2 = {"chmod", "777", file.getAbsolutePath()};
            Runtime.getRuntime().exec(args2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String path = file.getAbsolutePath();
        long len = file.length();
        Log.d(TAG, "autoInstallApk: " + path);
        Log.d(TAG, "len: " + len);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        } else {
            // 声明需要的临时的权限
            // 第二个参数，即第一步中配置的authorities
            Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".FileProvider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    public static int getVersionCode(Context context, String packageName) {
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(packageName, 0);
            return pInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // 捕获异常，正常情况下不会发生，除非包名错误
            e.printStackTrace();
            return -1;
        }
    }

    public static void foceStopApp(Context context,String packageName){
        try {
            // 获取ActivityManager服务实例
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

            // 获取ActivityManager类的Class对象
            Class<?> amClass = Class.forName("android.app.ActivityManager");

            // 获取forceStopPackage方法
            Method forceStopPackageMethod = amClass.getMethod("forceStopPackage", String.class);

            // 设置方法可访问（由于是隐藏方法，可能不可见）
            forceStopPackageMethod.setAccessible(true);

            // 调用forceStopPackage方法，传入要停止的应用包名
            forceStopPackageMethod.invoke(am, packageName);
        } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public static String getDeviceName() {
        return Build.MODEL;
    }

    public static String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}
